// web/src/app/api/(learn)/course/[courseId]/publish/route.ts

import {NextRequest, NextResponse} from "next/server";
import {currentUser} from "@/lib/auth";
import {db} from "@/lib/db";

export async function PATCH(
    req: NextRequest,
    {params}: { params: { courseId: string; chapterId: string } }
) {
    try {
        const user = await currentUser()
        if (!user) return new NextResponse('Unauthorized', {status: 401})

        const course = await db.course.findUnique({
            where: {
                id: params.courseId,
                userId: user.id
            },
            include: {chapters: {include: {muxData: true}}},
        })

        if (!course) {
            return new NextResponse('Unauthorized', {status: 401})
        }

        const hasPublishedChapter =
            course.chapters.some((c => c.isPublished))

        if (
            !course.title || !course.description || !course.imageUrl
            || !hasPublishedChapter || !course.categoryId
        ) {
            return new NextResponse('Missing required fields', {status: 401})
        }

        const publishedCourse = await db.course.update({
            where: {
                id: params.courseId,
                userId: user.id
            },
            data: {
                isPublished: true,
            }
        })

        return NextResponse.json(publishedCourse)
    } catch (e) {
        console.error('[COURSE_ID_PUBLISH]', e)
        return new NextResponse('Internal Server Error', {status: 500})
    }
}